import React, { useEffect, useState ,useRef,useImperativeHandle,forwardRef} from 'react'
import { Card, Divider,Button ,notification,Modal,Form, message} from 'antd';
import { EditOutlined, DoubleLeftOutlined, DoubleRightOutlined ,DeleteOutlined} from '@ant-design/icons';
import {getAllPool,delPool,addPool} from 'api/index'
import UploadPicture from 'components/Upload/index'
import LlxForm from 'components/LlxForm'
const { Meta } = Card;
// 新增弹框
const PoolRuleDialog = forwardRef((props, ref) => {
  const {isModalVisible, setIsModalVisible} = props

  const [formNew] = Form.useForm();

  const [refresh, setRefresh] = useState(false);

  useEffect(() => {
  refresh && setTimeout(() => setRefresh(false))
  }, [refresh])


  useImperativeHandle(ref, () => ({
    formNew
  }));



  useEffect(()=>{
    if(!isModalVisible) return
    setRefresh(true)

  },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps

  const loading = useRef(false)

   // 新增表单
   const newWordItem = props.type?[
  {label: '上传icon', name: 'icon', span: 20 , rules:[
    {
      required: true,
      message: '请上传icon'
    },
  ],render:()=>{
    return    <UploadPicture type={'icon'} pictureUrl={formNew.getFieldValue().icon} setPhoto={(value)=>formNew.setFieldsValue({...formNew.getFieldValue(),icon:value})}></UploadPicture>
  }},
  {label: '数量',type:'input', name: 'count' ,rules:[
    {
      required: true,
      message: '请输入数量'
    },
  ] , span: 20 },
  {label: '专辑数量',type:'input', name: 'albumCount' ,rules:[
    {
      required: true,
      message: '请输入专辑数量'
    },
  ] , span: 20 },
  {label: '分类名称',type:'input', name: 'poolName' ,rules:[
    {
      required: true,
      message: '请输入分类名称'
    },
  ] , span: 20 }
   ]:[
    {label: '上传icon', name: 'icon', span: 20 , rules:[
      {
        required: true,
        message: '请上传icon'
      },
    ],render:()=>{
      return    <UploadPicture type={'icon'}  pictureUrl={formNew.getFieldValue().icon} setPhoto={(value)=>formNew.setFieldsValue({...formNew.getFieldValue(),icon:value})}></UploadPicture>
    }},
    {label: '数量',type:'input', name: 'count' ,rules:[
      {
        required: true,
        message: '请输入数量'
      },
    ] , span: 20 },
    {label: '分类名称',type:'input', name: 'poolName' ,rules:[
      {
        required: true,
        message: '请输入分类名称'
      },
    ] , span: 20 }
     ]
   
   const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    formNew.validateFields().then(async()=>{

        const data  = {
          albumCount:formNew.getFieldValue().albumCount,
          count:formNew.getFieldValue().count,
          icon:formNew.getFieldValue().icon,
          id:formNew.getFieldValue().id,
          parentId:formNew.getFieldValue().parentId,
          poolName:formNew.getFieldValue().poolName,
          sort:formNew.getFieldValue().sort
        }
       await addPool(data)

       if(formNew.getFieldValue().id) {
        notification.success({
          message: '编辑成功',
          duration:1.5
        });
       } else {
        notification.success({
          message: '新增成功',
          duration:1.5
        });
       }

      
       formNew.resetFields()
       setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
       console.log(err);
    }).finally(()=>{
      loading.current=false
    })
   };

  const handleCancel = () => {
    formNew.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal destroyOnClose width={700} title="推送池分类规则" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
       <LlxForm form={formNew} preserve={true} labelCol={5} formItem={newWordItem} />
   </Modal>
})

function PoolRule() {
  
  const [video,setVideo] = useState([])
  const [book,setBook] = useState([])
  const [audio,setAudio] = useState([])
  const [type,setType] = useState(false)
  const [poolRuleModal,setPoolRuleModal] = useState(false)
  const pool = useRef()

   useEffect(()=>{
    getNewList()
   },[])
   

   const getNewList = async()=>{
    const res = await getAllPool()
    setVideo(res.result.filter(i => i.id === 3)[0].configList)
    setBook(res.result.filter(i => i.id === 1)[0].configList)
    setAudio(res.result.filter(i => i.id === 2)[0].configList)
   } 

   const editRule = (a,b,c) => {
     if(c){
      setType(true)
     } else {
      setType(false)
     }
    pool.current.formNew.setFieldsValue({
          albumCount: a.albumCount,
          count: a.count,
          icon: a.icon,
          id: a.id,
          parentId: a.parentId,
          poolName: a.poolName,
          sort: a.sort
    })

    setPoolRuleModal(true)
   }
   const goRight = async(a,b,c) => {
    switch(c){
      case 'book':
        if(b===book.length-1) return
        await addPool({
          sort:a.sort+1,id:a.id
         })
         await addPool({
          sort:book[b+1].sort-1,id:book[b+1].id
         })
      break
      case 'video':
        if(b===video.length-1) return
        await addPool({
          sort:a.sort+1,id:a.id
         })
         await addPool({
          sort:video[b+1].sort-1,id:video[b+1].id
         })
      break
      case 'audio':
        if(b===audio.length-1) return
        await addPool({
          sort:a.sort+1,id:a.id
         })
         await addPool({
          sort:audio[b+1].sort-1,id:audio[b+1].id
         })
        break
      default:
      return
    }
     getNewList()
   }
   const goLeft = async(a,b,c) => {
     if(b===0) return
    switch(c){
      case 'book':
        await addPool({
          sort:a.sort-1,id:a.id
         })
         await addPool({
          sort:book[b-1].sort+1,id:book[b-1].id
         })
      break
      case 'video':
        await addPool({
          sort:a.sort-1,id:a.id
         })
         await addPool({
          sort:video[b-1].sort+1,id:video[b-1].id
         })
      break
      case 'audio':
        await addPool({
          sort:a.sort-1,id:a.id
         })
         await addPool({
          sort:audio[b-1].sort+1,id:audio[b-1].id
         })
        break
      default:
      return
    }
     getNewList()
   }
   const delRule = async(a,b) => {
    await delPool(a.id)
    message.success('删除成功')
    getNewList()
   }
   const addRule = (a) => {
     switch(a){
       case 'book':
        setType(false)
        pool.current.formNew.setFieldsValue({
          albumCount: '',
          count: '',
          icon: '',
          id: '',
          parentId: 1,
          poolName: '',
          sort: book.length+1
    })
       break
       case 'video':
        setType(true)
        pool.current.formNew.setFieldsValue({
          albumCount: '',
          count: '',
          icon: '',
          id: '',
          parentId: 3,
          poolName: '',
          sort: video.length+1
    })
       break
       case 'audio':
        setType(false)
        pool.current.formNew.setFieldsValue({
          albumCount: '',
          count: '',
          icon: '',
          id: '',
          parentId: 2,
          poolName: '',
          sort: audio.length+1
    })
         break
       default:
       return
     }
   

    setPoolRuleModal(true)
   }

  return <div  className="app-content animate__animated animate__fadeIn">
      <Divider>图书馆</Divider>
    <div className="book-rule">
     <Button style={{marginBottom:'20px'}} type={'primary'} onClick={()=>addRule('book')}>新增分类</Button>

    <div>
    {
       book.length?book.map((i,j)=>{
         return <Card
         key={i.id}
         style={{ width: 220 }}
         cover={
           <img
             alt="example"
             src={i.icon}
           />
         }
         actions={[
           <EditOutlined onClick={()=>editRule(i,j)} key="edit" />,
           <DoubleLeftOutlined  onClick={()=>goRight(i,j,'book')}  key="left" />,
           <DoubleRightOutlined  onClick={()=>goLeft(i,j,'book')}  key="right" />,
           <DeleteOutlined  onClick={()=>delRule(i,j)} key="del"/>
         ]}
       >
         <Meta
           title={i.poolName}
           description={i.count?'配置数量：'+ i.count:'无数量'}
         />
       </Card>
       }):''
     }
    </div>
    
    </div>

    <Divider>电台</Divider>
    <div className="audio-rule">
    <Button style={{marginBottom:'20px'}}  type={'primary'} onClick={()=>addRule('audio')}>新增分类</Button>
    <div>
    {
       audio.length?audio.map((i,j)=>{
         return <Card
         key={i.id}
         style={{ width: 220 }}
         cover={
           <img
             alt="example"
             src={i.icon}
           />
         }
         actions={[
           <EditOutlined onClick={()=>editRule(i,j)} key="edit" />,
           <DoubleLeftOutlined  onClick={()=>goRight(i,j,'audio')}  key="left" />,
           <DoubleRightOutlined  onClick={()=>goLeft(i,j,'audio')}  key="right" />,
           <DeleteOutlined  onClick={()=>delRule(i,j)} key="del"/>
         ]}
       >
         <Meta
           title={i.poolName}
           description={i.count?'配置数量：'+ i.count:'无数量'}
         />
       </Card>
       }):''
     }
    </div>
    </div>

    <Divider>电影院</Divider>
    <div className="video-rule">
    <Button style={{marginBottom:'20px'}}  type={'primary'} onClick={()=>addRule('video')}>新增分类</Button>
    <div>
    {
       video.length?video.map((i,j)=>{
         return <Card
         key={i.id}
         style={{ width: 220 }}
         cover={
           <img
             alt="example"
             src={i.icon}
           />
         }
         actions={[
          <EditOutlined onClick={()=>editRule(i,j,true)} key="edit" />,
           <DoubleLeftOutlined  onClick={()=>goRight(i,j,'video')}  key="left" />,
           <DoubleRightOutlined  onClick={()=>goLeft(i,j,'video')}  key="right" />,
           <DeleteOutlined  onClick={()=>delRule(i,j)} key="del"/>
         ]}
       >
         <Meta
           title={i.poolName}
           description={i.count?'视频配置数量：'+ i.count:'无数量'}
         />
           <Meta
           title={''}
           description={i.count?'专辑配置数量：'+ i.albumCount:'无数量'}
         />
       </Card>
       }):''
     }
    </div>
    </div>

   <PoolRuleDialog getNewList={getNewList} type={type} ref={pool} isModalVisible={poolRuleModal} setIsModalVisible={setPoolRuleModal}></PoolRuleDialog>

  </div>
}



export default PoolRule